<?php

namespace common\widgets;

use home\assets\PageAsset;
use libs\Utils;
use Yii;
use yii\bootstrap\Html;
use yii\helpers\Url;
use yii\web\View;

/**
 * 动态表单重构类
 *
 * @package common\widgets
 */
class ActiveField extends \yii\bootstrap\ActiveField
{

    /**
     * 地区选择
     *
     * @return $this
     */
    public function select()
    {
        $inputName = Html::getInputName($this->model, $this->attribute);
        $valueId = Html::getAttributeValue($this->model, $this->attribute);

        $model = $this->model;
        $model = $model::className();
        $ids = $this->model->getParentIds();

        $parentId = 0;
        $selects = [];
        foreach($ids as $id){
            $datas = $model::getSelectDatas($parentId, $this->model->id);
            if($datas){
                $selects[] = Html::dropDownList($inputName, $id, $datas, [
                    'class' => 'form-control form-control-inline',
                    'ajax-select' => Url::to(['ajax/select', 'model' => $model, 'attribute' => $this->attribute, 'exclude' => $this->model->id]),
                ]);
            }else{
                $selects[] = Html::dropDownList($inputName, '', [], [
                    'class' => 'form-control form-control-inline',
                    'prompt' => '请选择',
                ]);
            }
            $parentId = $id;
        }

        $this->parts['{input}'] = join("", $selects);

        $js = <<<JS
        
$(document).off('change', 'select[ajax-select]');
$(document).on('change', 'select[ajax-select]', function(){
    var select = $(this);
    var url = $(this).attr('ajax-select');
    var parent_id = $(this).val();
    
    select.nextAll('select').remove();
    
    if(parent_id == $(this).children('option').eq(0).val()){
        return false;
    }
    
    $.post(url, {parent_id: parent_id}, function(datas){
        if(datas.html){
            select.after(datas.html);
        }
    }, 'json');
});

JS;

        Yii::$app->view->registerJs($js, View::POS_READY, 'ajax-select');

        return $this;
    }
}